import { Module, VuexModule, Mutation, Action } from 'vuex-module-decorators'
import Cookie from 'js-cookie'
import { OAuth } from '~/config/api'
import { $wAxios } from '@/utils/api'

@Module({
  name: 'oauth',
  stateFactory: true,
  namespaced: true
})
export default class OAuthModule extends VuexModule {
  // 用户头像
  icon = ''
  // 用户名
  name = ''
  // 用户类型 0： QQ
  type = 0
  // 用户ID
  userId = ''

  get ICON() {
    return this.icon
  }

  get TYPE() {
    return this.type
  }

  get NAME() {
    return this.name
  }

  /**
   * 设置用户数据
   */
  @Mutation
  OAUTH_SET_USER_DATA (data?: any) {
    if (data) {
      Object.assign(this, data)
    } else {
      Object.assign(this, {
        icon: '',
        name: '',
        type: 0,
        userId: ''
      })
    }
  }

  @Mutation
  OAUTH_CLEAR_USER_DATA () {
    this.icon = ''
    this.name = ''
    this.type = 0
    this.userId = ''
  }

  /**
   * 登录
   */
  @Action
  async LOGIN (data: any) {
    const resData = await $wAxios.$get(OAuth.qqUserInfo, {
      accessToken: data
    })
    // @ts-ignore
    Cookie.set(process.env.OAUTH_LOGIN, true)
    this.OAUTH_SET_USER_DATA(resData)
  }

  /**
   * 获取登录的用户信息
   */
  @Action
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  async SESSION_LOGIN () {
    const resData = await $wAxios.$get(OAuth.sessionLogin)
    this.OAUTH_SET_USER_DATA(resData)
  }

  /**
   * 退出登录
   */
  @Action
  async LOGOUT () {
    this.OAUTH_CLEAR_USER_DATA()
    // @ts-ignore
    Cookie.remove(process.env.OAUTH_LOGIN)
    await $wAxios.$get(OAuth.logout)
  }
}
